package org.example.mq.demo;

import org.example.mq.brokerserver.core.BasicProperties;
import org.example.mq.brokerserver.core.ExchangeType;
import org.example.mq.client.Channel;
import org.example.mq.client.Connection;
import org.example.mq.client.ConnectionFactory;
import org.example.mq.common.Consumer;
import org.example.mq.common.MqException;

import java.io.IOException;

//这个类表示一个消费者
//这个类在一个独立的服务器中被运行
public class DemoConsumer {
    public static void main(String[] args) throws IOException, InterruptedException, MqException {
        System.out.println("[DemoConsumer] 启动消费者");
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setPort(9090);

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare("testExchange", ExchangeType.DIRECT,true,false,null);
        channel.queueDeclare("testQueue",true,false,false,null);

        channel.basicConsume("testQueue", true, new Consumer() {
            @Override
            public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] payload) throws MqException, IOException {
                System.out.println("[DemoConsumer] 开始消费数据！ ");
                System.out.println("consumerTag="+consumerTag);
                System.out.println("basicProperties="+basicProperties);
                String payloadString = new String(payload,0, payload.length);
                System.out.println("payload="+payloadString);
                System.out.println("[DemoConsumer] 消费数据结束！");
            }
        });

        //由于消费者不知道生成者生成了多少，所以要一直等待
        while (true){
            Thread.sleep(500);
        }
    }
}
